/**
 * 
 */
package com.oron3.bouncer.genericgl;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Paint;

import com.oron3.bouncer.objects.shapes.Point;

/**
 * @author Ofek
 *
 */
public class Axes {
	private final GL3D gl3d;
	private final LabelMaker labelMaker;
	private final Paint mLabelPaint;
	private final Projector mProjector;
	private final float[] world = new float[4];
	private final float[] win = new float[4];
	private final int length;

	/**
	 * @param labelMaker
	 * 
	 */
	public Axes(final int length, final LabelMaker labelMaker, final Projector projector) {
		mProjector = projector;
		gl3d = new GL3D();
		gl3d.add(new Point(0, 0, 0), new Point(0, 0, length), new Point(length, 0, 0), new Point(0, length, 0));
		gl3d.add(0, 1, 0, 2, 0, 3);
		gl3d.prepare();
		this.labelMaker = labelMaker;
		mLabelPaint = new Paint();
		mLabelPaint.setTextSize(32);
		mLabelPaint.setAntiAlias(true);
		mLabelPaint.setARGB(0xff, 0x00, 0x00, 0x00);
		this.length = length;

	}

	public void init(final GL10 gl) {
		labelMaker.initialize(gl);
		labelMaker.beginAdding(gl);
		labelMaker.add(gl, "x", mLabelPaint);
		labelMaker.add(gl, "y", mLabelPaint);
		labelMaker.add(gl, "z", mLabelPaint);
		labelMaker.endAdding(gl);
	}

	public void draw(final GL10 gl, final float w, final float h) {

		labelMaker.beginDrawing(gl, w, h);
		drawLabel(gl, 0, 0, length, 2);
		drawLabel(gl, 0, length, 0, 1);
		drawLabel(gl, length, 0, 0, 0);
		labelMaker.endDrawing(gl);
		gl.glColor4f(0.5f, 0.5f, 1.0f, 1f);
		gl3d.draw(gl, GL10.GL_LINES);
	}

	private void drawLabel(final GL10 gl, final int x, final int y, final int z, final int labelId) {
		world[0] = x;
		world[1] = y;
		world[2] = z;
		world[3] = 1.0f;
		mProjector.project(world, 0, win, 0);
		final float sx = win[0];
		final float sy = win[1];
		final float height = labelMaker.getHeight(labelId);
		final float width = labelMaker.getWidth(labelId);
		final float tx = sx - width * 0.5f;
		final float ty = sy - height * 0.5f;
		labelMaker.draw(gl, tx, ty, labelId);
	}

}
